function downloadImage(url) {
    // 发送 HTTP GET 请求获取网页内容
    fetch(url)
        .then(response => response.text())
        .then(html => {
            // 使用选择器选取指定位置的图片元素
            let selector = "";
            if (/bus/.test(url)){
                selector = "body > div.container > div.row.movie > div.col-md-9.screencap > a > img";
            }else if (/javdb/.test(url)){
                selector = "body > section > div > div.video-detail > div.video-meta-panel > div > div.column.column-video-cover > a > img";
            }

            const imgElement = document.querySelector(selector);
            if (imgElement) {
                // 获取图片的 src 属性值
                let imageUrl = imgElement.src;


            } else {
                console.error('未能找到指定位置的图片元素。');
            }
        })
        .catch(error => console.error('爬取或下载图片时发生错误:', error));
}

function checkLocalFileExists(fileName) {
    // 调用本地文件系统的 API 来检查文件是否存在
    const fileExists = window.localStorage.getItem(fileName) !== null;

    return fileExists;
}

//* ******************************************************************************* *
/**
 * 查询115网盘是否拥有番号
 * @param {string} javId 番号
 * @param {Function} callback 回调函数
 */
function search115Data(javId, callback) {
    //异步请求搜索115番号 //115查询
    let javId2 = javId.replace(/(-)/g, ""); //把番号-去除，例如ABC-123 =》 ABC123
    let javId3 = javId.replace(/(-)/g, "00"); //把番号-替换为00，例如CCVR-065 =》 CCVR00065
    let javId4 = javId.replace(/(-)/g, "-0"); //把番号-替换为-0，例如DSVR-584 =》 DSVR-0584
    console.log("115_search_var", `${javId}|${javId2}|${javId3}|${javId4}`)

    //保存查询关键词参数
    //GM_setValue("115_search_var", `${javId}|${javId2}|${javId3}|${javId4}`);

    let url = `https://webapi.115.com/files/search?search_value=${javId}%20${javId2}%20${javId3}%20${javId4}&format=json`;
    // 使用 fetch 发送 GET 请求
    fetch(url)
        .then(response => {
            // 检查响应是否成功
            if (!response.ok) {
                throw new Error('Network response was not ok');
                callback(false, null, null);
            }
            // 解析JSON
            return response.json();
        })
        .then(resultJson => {
            // 处理JSON数据
            if (resultJson.count > 0) {
                let pickcode = '';
                let cid = '';
                let isRecord = false
                let isFavorite = false
                let reg = new RegExp(GM_getValue("115_search_var"), "gi");
                for (let i = 0; i < resultJson.data.length; i++) {
                    let row = resultJson.data[i];
                    if (row.play_long && (row.n.search(reg) >= 0)) { //iv vdi ico play_long
                        pickcode = row.pc;
                        cid = row.cid

                        if (row.m == "1"){
                            isFavorite = true;
                        }

                        var flList = row.fl;
                        if (flList){
                            for (let j = 0; j < flList.length; j++) {
                                var flagName = flList[j].name;
                                if (flagName == "A▓▓" || flagName == "A██"){
                                    isRecord = true;
                                    break;
                                }
                            }
                        }

                        callback(true, `https://v.anxia.com/?pickcode=${pickcode}`, pickcode, `https://115.com/?cid=${cid}&offset=0&mode=wangpan`, isRecord, isFavorite);
                        return;
                    }
                }
            }
        })
        .catch(error => {
            // 处理请求过程中出现的错误
            console.error('There was a problem with your fetch operation:', error);
            callback(false, null, null);
        });

}

//* ******************************************************************************* *
function addPreloadImage() {
    let mm = document.getElementsByClassName("main")[0];
    if (mm) {
        /* 按钮面板 */
        let preloadDiv = document.createElement("div");
        preloadDiv.id = "preload-image";


        /* 大预览图 */
        let img = document.createElement("image");
        img.style.width = "640px";
        img.style.height = "480px";
        img.src = "https://www.fanbus.cfd/pics/cover/7zdk_b.jpg";
        img.title = "超絶美女教師を全裸羞恥で興奮させOKさせろ";

        preloadDiv.appendChild(img);

        mm.appendChild(preloadDiv);
    }
}

function addSelectEvent() {
    var elements = document.querySelectorAll('[role]'); // 选取所有具有"data-customAttr"自定义属性的元素
    for (var i = 0; i < elements.length; i++) {
        var customValue = elements[i].getAttribute("role"); // 获取每个元素的自定义属性值
        if (customValue == "listitem") {
            elements[i].addEventListener("click", function(event) {
                // 在这里编写处理选择事件的代码
                let listItem = event.currentTarget
                let url = listItem.getElementsByClassName("url")[0];
                console.log(url.innerText); // 输出自定义属性值到控制台
            });

            // let url = elements[i].getElementsByClassName("url")[0];
            // console.log(url.innerText); // 输出自定义属性值到控制台
        }
    }
}

function logItemList(){
    let elements = document.querySelectorAll('[role]'); // 选取所有具有"data-customAttr"自定义属性的元素
    let logText = "";
    for (var i = 0; i < elements.length; i++) {
        var customValue = elements[i].getAttribute("role"); // 获取每个元素的自定义属性值
        if (customValue == "listitem") {
            let url = elements[i].getElementsByClassName("url")[0];
            // console.log(url.innerText); // 输出自定义属性值到控制台
            logText = logText + url.innerText + "\n";
        }
    }
    console.log(logText);
    logText = logText + "\n"

    let addrDiv = document.getElementById("addr-list");
    let allText = addrDiv.innerText + logText;
    addrDiv.innerText = allText;
}

function imageWindowList(){
    let sss = document.createElement("script");
    sss.src = "https://unpkg.com/axios/dist/axios.min.js";
    document.head.appendChild(sss);

    let elements = document.querySelectorAll('[role]'); // 选取所有具有"data-customAttr"自定义属性的元素
    for (var i = 0; i < elements.length; i++) {
        var customValue = elements[i].getAttribute("role"); // 获取每个元素的自定义属性值
        if (customValue == "listitem") {
            let labelEle = elements[i].getElementsByClassName("label")[0];
            let labelText = labelEle.textContent
            const codeText = parseCode(labelText);

            let urlEle = elements[i].getElementsByClassName("url")[0];
            const codeUrl = urlEle.innerText;

            let domainEle = elements[i].getElementsByClassName("domain")[0];
            removeFirstTextNode(domainEle);

            let jdbBtn = elements[i].getElementsByClassName("jdb-button")[0];
            if (!jdbBtn) {
                jdbBtn = document.createElement("button");
                jdbBtn.className = "jdb-button";
                jdbBtn.textContent = "转JDB";
                jdbBtn.addEventListener("click", function (event) {
                    jumpJDB(codeText);
                });

                domainEle.appendChild(jdbBtn);
            }

            // let preloadBtn = elements[i].getElementsByClassName("preload-button")[0];
            // if (!preloadBtn) {
            //     preloadBtn = document.createElement("button");
            //     preloadBtn.className = "preload-button";
            //     preloadBtn.textContent = "预览";
            //     preloadBtn.addEventListener("click", function (event) {
            //         showImageWindow(codeUrl);
            //     });
            //
            //     domainEle.appendChild(preloadBtn);
            // }

            let search115Btn = elements[i].getElementsByClassName("search115-button")[0];
            if (!search115Btn) {
                search115Btn = document.createElement("button");
                search115Btn.className = "search115-button";
                search115Btn.textContent = "搜索";
                search115Btn.addEventListener("click", function (event) {
                    search115Data(codeText, function (isRet, playAddr, pickcode, lookAddr, isRecord, isFavorite){
                        if (isRet){
                            let btnText = "播放";

                            if (isRecord){
                                btnText += "■";
                            }

                            if (isFavorite){
                                btnText += "★";
                            }

                            search115Btn.textContent = btnText;
                            search115Btn.addEventListener("click", function (event){
                                var newWindow = window.open(playAddr, '_blank'); // 在新标签页中打开URL
                                if (!newWindow) {
                                    // 窗口可能被浏览器阻止了
                                    alert('请允许浏览器打开新窗口或标签页。');
                                }
                            });
                        }
                    });
                });

                domainEle.appendChild(search115Btn);
            }
        }
    }
}

function clearAddrList(){
    let addrDiv = document.getElementById("addr-list");
    addrDiv.innerText = "";
}

async function fetchAndExtractData(url, selector) {
    try {
        // 使用fetch API发送跨域请求
        const response = await fetch(url);
        const text = await response.text();

        // 使用DOMParser解析HTML
        const parser = new DOMParser();
        const doc = parser.parseFromString(text, 'text/html');

        // 使用querySelector选择元素并提取值
        const element = doc.querySelector(selector);
        const value = element ? element.src : null;

        return value;
    } catch (error) {
        console.error('爬取或下载图片时发生错误:', error);
        return null;
    }
}

async function fetchAndExtractData2(url, selector) {
    try {
        // 发送跨域请求
        const response = await axios.get(url);
        const html = response.data;

        // 解析HTML
        const parser = new DOMParser();
        const doc = parser.parseFromString(html, 'text/html');

        // 选择元素并提取值
        const element = doc.querySelector(selector);
        const value = element ? element.textContent : null;

        return value;
    } catch (error) {
        console.error('Error fetching and extracting data:', error);
        return null;
    }
}
function showImageWindow(codeUrl){
    // 发送 HTTP GET 请求获取网页内容
    // fetch(codeUrl)
    //     .then(response => response.text())
    //     .then(html => {
    //         // 使用选择器选取指定位置的图片元素
    //         let selector = "";
    //         if (/bus/.test(codeUrl)){
    //             selector = "body > div.container > div.row.movie > div.col-md-9.screencap > a > img";
    //         }else if (/javdb/.test(codeUrl)){
    //             selector = "body > section > div > div.video-detail > div.video-meta-panel > div > div.column.column-video-cover > a > img";
    //         }
    //
    //         const imgElement = document.querySelector(selector);
    //         if (imgElement) {
    //             // 获取图片的 src 属性值
    //             let imageUrl = imgElement.src;
    //
    //             let floatingImage = document.getElementById("floatingImage");
    //             floatingImage.src = imageUrl;
    //
    //             let floatingWindow = document.getElementById("image-window");
    //             floatingWindow.style.display = "block";
    //
    //         } else {
    //             console.error('未能找到指定位置的图片元素。');
    //         }
    //     })
    //     .catch(error => console.error('爬取或下载图片时发生错误:', error));

    let selector = "";
    if (/bus/.test(codeUrl)){
        selector = "body > div.container > div.row.movie > div.col-md-9.screencap > a > img";
    }else if (/javdb/.test(codeUrl)){
        selector = "body > section > div > div.video-detail > div.video-meta-panel > div > div.column.column-video-cover > a > img";
    }


    fetchAndExtractData2(codeUrl, selector)
        .then(imageUrl=>{
            let floatingImage = document.getElementById("floatingImage");
            floatingImage.src = imageUrl;

            let floatingWindow = document.getElementById("image-window");
            floatingWindow.style.display = "block";
        });

}

function jumpJDB(avcode){
    let jdbUrl = "https://javdb367.com/search?q=" + avcode + "&f=all";

    parseJdbUrl(jdbUrl);

    // var newWindow = window.open(jdbUrl, '_blank'); // 在新标签页中打开URL
    // // 可选：检查窗口是否成功打开
    // if (!newWindow) {
    //     // 窗口可能被浏览器阻止了
    //     alert('请允许浏览器打开新窗口或标签页。');
    // }
}

function parseCode(str){
    // let str = "AB12345-67890"; // 示例字符串，注意它不完全符合你的模式
    let pattern = /^[a-zA-Z]{2,5}-[0-9]{2,5}/; // 定义正则表达式

// 使用match方法匹配字符串
    let matchResult = str.match(pattern);

    if (matchResult) {
        // 如果匹配成功，matchResult[0]将包含完整的匹配项
        console.log(matchResult[0]); // 输出匹配到的字符串
        return matchResult[0];

    } else {
        console.log("没有匹配到字符串");
        return null;
    }
}

function getDomainFromUrl(url) {
    // 创建一个新的URL对象
    const urlObj = new URL(url);
    // 使用hostname属性获取域名
    return urlObj.hostname;
}

function parseJdbUrl(targetUrl){
    let domain = getDomainFromUrl(targetUrl);

    fetch(targetUrl) // 请求用户指定的页面
        .then(response => response.text())
        .then(html => {
            console.log(html);
            const parser = new DOMParser();
            const doc = parser.parseFromString(html, 'text/html');
            const movieList = doc.getElementsByClassName('movie-list');
            if (movieList.length > 0) {
                const firstElement = movieList[0];
                const firstLink = firstElement.querySelector('a');
                if (firstLink) {
                    const href = firstLink.getAttribute('href');

                    var fullUrl = "http://" + domain + href;

                    var newWindow = window.open(fullUrl, '_blank'); // 在新标签页中打开URL
                    if (!newWindow) {
                        // 窗口可能被浏览器阻止了
                        alert('请允许浏览器打开新窗口或标签页。');
                    }
                }
            }
        })
        .catch(err => console.error('Error fetching and parsing HTML', err));
}

function removeFirstTextNode(element) {
    // 检查元素是否存在
    if (!element) return;

    // 遍历子节点
    for (let i = 0; i < element.childNodes.length; i++) {
        // 检查节点是否是文本节点
        if (element.childNodes[i].nodeType === 3) {
            // 如果是，则移除它
            element.removeChild(element.childNodes[i]);
            // 由于移除了节点，列表的长度已经改变，我们可以停止循环
            break;
        }
    }
}

async function handleFolderSelection() {
    try {
        // 请求用户选择一个目录
        const directoryHandle = await window.showDirectoryPicker();

        if (!directoryHandle) {
            console.log('User did not select a directory.');
            return;
        }

        // 使用 values() 迭代器遍历目录中的文件和子目录
        for await (const entry of directoryHandle.values()) {
            if (entry.kind === 'file') {
                // 处理文件
                console.log('File:', entry.name);
                // 你也可以获取文件的 FileSystemFileHandle 来进一步操作文件
                // const fileHandle = await entry.getFileHandle();
            } else if (entry.kind === 'directory') {
                // 处理子目录
                console.log('Directory:', entry.name);
                // 你可以递归地调用这个函数来处理子目录
                // 注意：这里需要小心递归深度，避免无限循环或堆栈溢出
            }
        }
    } catch (error) {
        console.error('Error accessing the directory:', error);
    }
}

function addAddrsPanel(){
    /* 番号范围面板 */
    var ppp1 = document.createElement("p");
    ppp1.style.backgroundColor = "#eee";

    /* 清除列表 */
    var btnClear= document.createElement("button");
    btnClear.style.marginLeft = "30px";
    btnClear.style.marginRight = "10px";
    btnClear.appendChild(document.createTextNode("清除"));
    btnClear.addEventListener("click", clearAddrList);
    ppp1.appendChild(btnClear);

    /* 播放地址列表 */
    var addrdiv = document.createElement("div");
    // addrdiv.className = "movie";
    addrdiv.id = "addr-list";

    /* 右侧容器 */
    var conterDiv = document.createElement("div");
    conterDiv.style.width = "300px";
    conterDiv.style.overflowY = "scroll";
    conterDiv.appendChild(ppp1);
    conterDiv.appendChild(addrdiv);

    /* 插入到页面中 */
    var element = document.getElementsByClassName("main")[0];
    if (element){
        element.append(conterDiv);
    }

}

function addButton() {
    let hh = document.getElementsByClassName("header")[0];
    if (hh) {
        /* 读取按钮 */
        let loadBtn = document.createElement("button");
        loadBtn.class = "normalBtn";
        loadBtn.textContent = "加载..."
        loadBtn.addEventListener("click", logItemList);

        /* 读取按钮 */
        let showImgBtn = document.createElement("button");
        showImgBtn.class = "normalBtn";
        showImgBtn.textContent = "显示预览图"
        showImgBtn.addEventListener("click", imageWindowList);

        /* 读取按钮 */
        let readFileListBtn = document.createElement("button");
        readFileListBtn.class = "normalBtn";
        readFileListBtn.textContent = "读取目录"
        readFileListBtn.addEventListener("click", handleFolderSelection);

        hh.appendChild(loadBtn);
        hh.appendChild(showImgBtn);
        hh.appendChild(readFileListBtn);
    }
}

function addImageWindow(){
    // 创建一个新的悬浮窗元素
    var floatingWindow = document.createElement('div');
    floatingWindow.id = "image-window"
    floatingWindow.className = 'floating-window';
    floatingWindow.style.width = '800px';
    floatingWindow.style.height = '540px';
    floatingWindow.style.position = 'fixed';
    floatingWindow.style.top = '50%';
    floatingWindow.style.left = '50%';
    floatingWindow.style.transform = 'translate(-50%, -50%)';
    floatingWindow.style.background = 'rgba(0, 0, 0, 0.6)';
    floatingWindow.style.color = 'white';
    floatingWindow.style.display = 'none';

// 创建一个新的图片元素
    var floatingImage = document.createElement('img');
    floatingImage.id = 'floatingImage';
    floatingImage.style.width = '100%';
    floatingImage.style.height = '100%';
    // floatingImage.src = "https://www.fanbus.cfd/pics/cover/7zdk_b.jpg";

// 创建一个新的关闭按钮元素
    var closeBtn = document.createElement('button');
    closeBtn.id = 'closeBtn';
    closeBtn.textContent = '关闭';
    closeBtn.style.position = 'absolute';
    closeBtn.style.top = '10px'; // 调整为合适的位置
    closeBtn.style.right = '10px'; // 调整为合适的位置
    closeBtn.addEventListener('click', function() {
        floatingWindow.style.display = 'none';
    });

// 将图片和关闭按钮添加到悬浮窗中
    floatingWindow.appendChild(floatingImage);
    floatingWindow.appendChild(closeBtn);

// 将悬浮窗添加到文档体中
    document.body.appendChild(floatingWindow);
}

function main(){
    // addPreloadImage();
    // addSelectEvent();
    // logItemList();

    addButton();
    addAddrsPanel();
    addImageWindow();

    // search115Data("ipx-353", function (isRet, playAddr, pickcode, lookAddr, isRecord, isFavorite){
    //     if (isRet){
    //         alert('搜索115成功。');
    //     }
    // });
}

main();
